<template>
  <div class="uploadImg">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="httpRequest"
      :before-upload="beforeUpload"
    >
      <img
        v-if="value"
        :src="value"
        class="avatar"
        @click.stop.prevent="lookClick"
      >
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <!-- 添加图片删除按钮 -->
    <div v-if="value" class="delete" @click="del">x</div>
    <!-- 进度条 -->
    <el-progress v-if="isShow" :percentage="percentage" />
    <!-- 图片预览 -->
    <el-dialog :visible.sync="look" title="图片预览" width="600px">
      <div style="text-align: center">
        <img style="width: 80%" :src="value" alt="">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Cos from 'cos-js-sdk-v5'
const cos = new Cos({
  // 秘钥,在实际开发中一般不会这么写，一般是获取个人用户信息时传递过来，然后在这里用上
  SecretId: 'AKIDfDVWHm0xd3C4g15sOdcKlvpRmqdAPO6X',
  SecretKey: 'B5i5B1astc4FBqELDn68tOcYDckbBUWI'
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // imageUrl: '',
      percentage: 0, // 进度条的数据
      isShow: false, // 进度条的显示与隐藏
      look: false // 图片预览
    }
  },
  methods: {
    beforeUpload(file) {
      // console.log('beforeUpload', file)
      const isImg = file.type === 'image/png' || file.type === 'image/jpeg'
      if (!isImg) {
        this.$message.success('请上传png,jpg格式图片')
      }
      const limitImg = file.size / 1024 / 1024 < 1
      if (!limitImg) {
        this.$message.success('请上传1mb内的图片')
      }
      return isImg || limitImg
    },
    httpRequest(res) {
      // 每次进入上传就显示进度条
      this.isShow = true
      //   每次上传都重置百分比
      this.percentage = 0
      // 重点：res.file,它就是我们需要传递给服务器的文件对象
      console.log(res)
      cos.putObject(
        {
          Bucket: 'hr-1309565688' /* 填入您自己的存储桶，必须字段 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: res.file.uid + '', //  '存储的标识 ，可以使用文件的uid或者文件名之类都可以，但是一定要是字符串' /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percentage = progressData.percent * 100
            if (progressData.percent === 1) {
              setInterval(() => {
                this.isShow = false
              }, 1000)
            }
            // 上传进度，可以实时获取上传的进度百分比
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          // err:代表上传出错的的错误信息  data:上传成功的返回值，包括上传的图片地址
          console.log(err || data)
          console.log(data.Location)
          //   this.imageUrl = 'http://' + data.Location
          //   修改图片地址
          this.$emit('input', 'http://' + data.Location)
        }
      )
    },
    // 删除按钮
    del() {
      this.$emit('input', '')
    },
    // 图片预览点击事件
    lookClick() {
      this.look = true
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.uploadImg {
  position: relative;
  width: 178px;
  &:hover {
    .delete {
      display: block;
    }
  }
  .delete {
    position: absolute;
    right: 5px;
    top: 5px;
    cursor: pointer;
    display: none;
  }
}
</style>
